import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/focus__model.dart';
import '../../../models/category_model.dart';
import '../../../models/plist_model.dart';
import '../../../services/httpsClient.dart';

class HomeController extends GetxController {
  //TODO: Implement HomeController

  HttpsClient httpsClient = HttpsClient();
  // 浮动导航开关
  RxBool flag = false.obs;

  // ScrollController，滚动控制器
  final ScrollController scrollController = ScrollController();

  RxList<FocusModelItem> swiperList = <FocusModelItem>[].obs; // 响应式数据
  RxList<CategoryModelItem> categroyList = <CategoryModelItem>[].obs;
  // 热销臻品banner数据
  RxList<FocusModelItem> bestSellingSwiperList = <FocusModelItem>[].obs;
  RxList<PlistItemModel> bestSellingList = <PlistItemModel>[].obs;
  RxList<PlistItemModel> hotSellinglist = <PlistItemModel>[].obs;

  final count = 0.obs;

  @override
  void onInit() {
    super.onInit();
    // 请求轮播图方法
    getFocusData();
    // 绑定滚动事件方法
    scrollControlleraddListener();
    // 请求分类方法
    getCategoryData();
    // 热销甄选轮播图
    getBestSellingSwiper();
    // 获取热销甄选商品列表
    getBestSellingList();
    // 获取热门商品
    gethotSellingList();
  }

  @override
  void onClose() {
    super.onClose();
  }

// 板顶滚动事件
  void scrollControlleraddListener() {
    scrollController.addListener(() {
      if (scrollController.position.pixels > 10) {
        if (flag.value == false) {
          flag.value = true;
          update();
        }
      } else {
        if (flag.value == true) {
          flag.value = false;
          update();
        }
      }
    });
  }

  void increment() => count.value++;

  // 请求轮播图数据
  void getFocusData() async {
    var res = await httpsClient.get('api/focus');
    if (res != null) {
      var focus = FocusModel.fromJson(res.data);
      swiperList.value = focus.result;
      update();
    }
  }

  // 请求分类数据
  void getCategoryData() async {
    var res = await httpsClient.get('api/bestCate');

    if (res != null) {
      var category = CategoryModel.fromJson(res.data);
      categroyList.value = category.result;
      update();
    }
  }

  // 获取热销臻品轮播图
  void getBestSellingSwiper() async {
    var res = await httpsClient.get('api/focus');

    if (res != null) {
      var bestSell = FocusModel.fromJson(res.data);
      bestSellingSwiperList.value = bestSell.result;
      update();
    }
  }

  // 获取热销甄选的商品数据
  void getBestSellingList() async {
    var res = await httpsClient.get('api/plist?is_hot=1');

    if (res != null) {
      var plist = PlistModel.fromJson(res.data);
      bestSellingList.value = plist.result;
      update();
    }
  }

  // 获取热门商品数据
  void gethotSellingList() async {
    var res = await httpsClient.get('api/plist?is_best=1');

    if (res != null) {
      var hotList = PlistModel.fromJson(res.data);
      hotSellinglist.value = hotList.result;
      update();
    }
  }
}
